﻿using MiscUtil.IO;
using MiscUtil.Conversion;
using System.IO;

public static class LuaBitConverterHelper
{
    public static EndianBinaryReader OpenReader(byte[] content)
    {
        return new EndianBinaryReader(BigEndianBitConverter.Big, new MemoryStream(content));
    }

    public static void FinishRead(EndianBinaryReader br)
    {
        br.Close();
    }

    public static int ReadInt32(EndianBinaryReader br)
    {
        return br.ReadInt32();
    }

    public static float ReadInt64(EndianBinaryReader br)
    {
        return br.ReadInt64();
    }

    public static float ReadFloat(EndianBinaryReader br)
    {
        return br.ReadSingle();
    }

    public static bool ReadBool(EndianBinaryReader br)
    {
        return br.ReadBoolean();
    }

    public static string ReadString(EndianBinaryReader br)
    {
        MemoryStream ms = new MemoryStream();
        while(true)
        {
            byte b = br.ReadByte();
            if(b == 0)
            {
                break;
            }
            else
            {
                ms.WriteByte(b);
            }
        }
        return System.Text.Encoding.UTF8.GetString(ms.ToArray());
    }

    public static void Seek(EndianBinaryReader br, int offset)
    {
        br.Seek(offset, SeekOrigin.Current);
    }

    public static EndianBinaryWriter OpenWrite()
    {
        return new EndianBinaryWriter(BigEndianBitConverter.Big, new MemoryStream());
    }

    public static byte[] FinishWrite(EndianBinaryWriter bw)
    {
        byte[] content = ((MemoryStream)bw.BaseStream).ToArray();
        bw.Close();
        return content;
    }

    public static void WriteInt32(EndianBinaryWriter bw, int value)
    {
        bw.Write(value);
    }

    public static void WriteInt64(EndianBinaryWriter bw, long value)
    {
        bw.Write(value);
    }

    public static void WriteInt16(EndianBinaryWriter bw, int value)
    {
        bw.Write(value);
    }

    public static void WriteByte(EndianBinaryWriter bw, byte value)
    {
        bw.Write(value);
    }
    
    public static void WriteFloat(EndianBinaryWriter bw, float value)
    {
        bw.Write(value);
    }

    public static void WriteBool(EndianBinaryWriter bw, bool value)
    {
        bw.Write(value);
    }

    public static void WriteString(EndianBinaryWriter bw, string value)
    {
        bw.Write(System.Text.UTF8Encoding.UTF8.GetBytes(value));
        bw.Write((byte)0);
    }
}
